#!/usr/bin/env python
#coding=utf-8

import fairy,json
import BaseHTTPServer,SimpleHTTPServer
import os,io,shutil
# import logging
import urlparse
import sys

hooker = fairy.Hooker()


# log_path = './run_server_logs.log'
# logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=log_path)

class SETHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):        
    def send_datas(self,contents):
        #指定返回编码
        enc = "UTF-8"
        f = io.BytesIO()
        f.write(contents)
        f.seek(0)  
        self.send_response(200)  
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", str(len(contents)))  
        self.end_headers() 
        shutil.copyfileobj(f,self.wfile)


    def getQuery(self):
        query = urlparse.urlparse(self.path).query
        return dict([(k,v[0]) for k,v in urlparse.parse_qs(query).items()])

    def hook(self):
        query = self.getQuery()
        hooker.addTask(query.get("project"),query.get("branch"))
        return query

            
    def do_GET(self):
        self.send_datas(self.hook())
        
    def do_POST(self):
        self.send_datas(self.hook())

def startServer():
	httpd = BaseHTTPServer.HTTPServer(("",10000), SETHandler)
	httpd.serve_forever()

if __name__ == "__main__":
	startServer()



